package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.SkuMapper;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.utils.CacheKey;
import org.apache.http.HttpHost;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SkuService.class)
public class SkuServiceImpl implements SkuService {

    @Autowired
    private SkuMapper skuMapper;

    /**
     * 返回全部记录
     *
     * @return
     */
    public List<Sku> findAll() {
        return skuMapper.selectAll();
    }

    /**
     * 分页查询
     *
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Sku> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        Page<Sku> skus = (Page<Sku>) skuMapper.selectAll();
        return new PageResult<Sku>(skus.getTotal(), skus.getResult());
    }

    /**
     * 条件查询
     *
     * @param searchMap 查询条件
     * @return
     */
    public List<Sku> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return skuMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     *
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Sku> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        Page<Sku> skus = (Page<Sku>) skuMapper.selectByExample(example);
        return new PageResult<Sku>(skus.getTotal(), skus.getResult());
    }

    /**
     * 根据Id查询
     *
     * @param id
     * @return
     */
    public Sku findById(String id) {
        return skuMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增
     *
     * @param sku
     */
    public void add(Sku sku) {
        skuMapper.insert(sku);
    }

    /**
     * 修改
     *
     * @param sku
     */
    public void update(Sku sku) {
        skuMapper.updateByPrimaryKeySelective(sku);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void delete(String id) {
        skuMapper.deleteByPrimaryKey(id);
    }

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 把所有商品及sku的价格存入redis中
     */
    @Override
    public void saveAllPriceToRedis() {
        //判断缓存中是否有价格数据
        if (!redisTemplate.hasKey(CacheKey.SKU_PRICE)) { //没有
            System.out.println("加载全部商品价格");
            List<Sku> skuList = skuMapper.selectAll();
            for (Sku sku : skuList) {
                if ("1".equals(sku.getStatus())) {
                    redisTemplate.boundHashOps(CacheKey.SKU_PRICE).put(sku.getId(), sku.getPrice());
                }
            }
        } else {
            System.out.println("已经存在商品价格!");
        }
    }

    @Override
    public Integer findPrice(String skuId) {
        return (Integer) redisTemplate.boundHashOps(CacheKey.SKU_PRICE).get(skuId);
    }

    @Override
    public void savePriceToRedisById(String skuId, Integer price) {
        redisTemplate.boundHashOps(CacheKey.SKU_PRICE).put(skuId, price);
    }

    @Override
    public void deletePriceFromRedisById(String skuId) {
        redisTemplate.boundHashOps(CacheKey.SKU_PRICE).delete(skuId);
    }


    /**
     * 把所有的sku导入elasticsearch中
     */
    @Override
    public void importSkuListToEs() {
        //连接rest接口
        System.out.println("开始连接索引数据");
        HttpHost http = new HttpHost("127.0.0.1", 9200, "http");
        //获取rest构建器
        RestClientBuilder builder = RestClient.builder(http);
        //获取高级客户端对象
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(builder);

        //判断索引为sku中是否有数据,有数据直接结束方法
        if (CountEs(restHighLevelClient) > 0) {
            System.out.println("已存在数据!");
            return;
        }

        //没有数据,从数据库引入数据
        System.out.println("准备引入数据");
        Map searchMap = new HashMap();
        searchMap.put("status", "1");
        //由于数据过于庞大,一次无法全部导入,所以需要用到分页技术
        int pageNum = 1;
        while (true) {
            System.out.println("pageNum:" + pageNum);
            PageResult pageResult = findPage(searchMap, pageNum, 1000);
            List<Sku> skuList = pageResult.getRows(); //获得1000条sku
            if (skuList.size() > 0)
                importToEs(restHighLevelClient, skuList);
            else
                break;
            pageNum++;
        }
        System.out.println("索引库数据完成");
    }


    /**
     * 根据订单明细批量扣除库存
     *
     * @param orderItemList
     * @return
     */
    @Override
    @Transactional
    public boolean deductionStock(List<OrderItem> orderItemList) {
        //判断是否可以扣除库存
        boolean flag = true;
        for (OrderItem item : orderItemList) {
            Sku sku = findById(item.getSkuId());
            if (sku == null || !"1".equals(sku.getStatus()) || sku.getNum() < item.getNum()) {
                flag = false;
                break;
            }
        }
        if(flag) { //可以扣除库存并添加销量
            for (OrderItem item : orderItemList) {
                skuMapper.deductionStock(item.getSkuId(),item.getNum());
                skuMapper.addSaleNum(item.getSkuId(),item.getNum());
            }
        }
        return flag;
    }


    /**
     * 计算总记录数
     *
     * @param restHighLevelClient
     * @return
     */
    private long CountEs(RestHighLevelClient restHighLevelClient) {
        SearchRequest searchRequest = new SearchRequest("sku");
        searchRequest.types("doc"); //设置查询的类型
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchRequest.source(searchSourceBuilder);
        //获取查询结果
        SearchResponse search = null;
        try {
            search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
        SearchHits hits = search.getHits(); //获得hits对象
        long totalHits = hits.totalHits; //计算出总击中数,即总条数
        return totalHits;
    }

    /**
     * 封装请求对象,并获取响应结果
     *
     * @param restHighLevelClient
     * @param skuList
     */
    private void importToEs(RestHighLevelClient restHighLevelClient, List<Sku> skuList) {
        BulkRequest bulkRequest = new BulkRequest();
        for (Sku sku : skuList) {
            //封装请求对象
            IndexRequest indexRequest = new IndexRequest("sku", "doc", sku.getId() + "");
            //封装请求参数
            Map skuMap = new HashMap();
            skuMap.put("name", sku.getName());
            skuMap.put("price", sku.getPrice());
            skuMap.put("image", sku.getImage());
            skuMap.put("createTime", sku.getCreateTime());
            skuMap.put("spuId", sku.getSpuId());
            skuMap.put("categoryName", sku.getCategoryName());
            skuMap.put("brandName", sku.getBrandName());
            skuMap.put("saleNum", sku.getSaleNum());
            skuMap.put("commentNum", sku.getCommentNum());
            skuMap.put("spec", JSON.parseObject(sku.getSpec(), Map.class));
            indexRequest.source(skuMap);
            bulkRequest.add(indexRequest);
        }
        System.out.println("开始导入索引库");
        restHighLevelClient.bulkAsync(bulkRequest, RequestOptions.DEFAULT, new ActionListener<BulkResponse>() {
            /**
             * 成功走这里
             * @param bulkItemResponses
             */
            @Override
            public void onResponse(BulkResponse bulkItemResponses) {
                System.out.println("导入成功," + bulkItemResponses.status());
            }

            /**
             * 失败走这里
             * @param e
             */
            @Override
            public void onFailure(Exception e) {
                System.out.println("导入失败," + e.getMessage());
            }
        });
        System.out.println("导入完成!");
    }


    /**
     * 构建查询条件
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 商品id
            if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                criteria.andLike("id", "%" + searchMap.get("id") + "%");
            }
            // 商品条码
            if (searchMap.get("sn") != null && !"".equals(searchMap.get("sn"))) {
                criteria.andLike("sn", "%" + searchMap.get("sn") + "%");
            }
            // SKU名称
            if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                criteria.andLike("name", "%" + searchMap.get("name") + "%");
            }
            // 商品图片
            if (searchMap.get("image") != null && !"".equals(searchMap.get("image"))) {
                criteria.andLike("image", "%" + searchMap.get("image") + "%");
            }
            // 商品图片列表
            if (searchMap.get("images") != null && !"".equals(searchMap.get("images"))) {
                criteria.andLike("images", "%" + searchMap.get("images") + "%");
            }
            // SPUID
            if (searchMap.get("spuId") != null && !"".equals(searchMap.get("spuId"))) {
                criteria.andLike("spuId", "%" + searchMap.get("spuId") + "%");
            }
            // 类目名称
            if (searchMap.get("categoryName") != null && !"".equals(searchMap.get("categoryName"))) {
                criteria.andLike("categoryName", "%" + searchMap.get("categoryName") + "%");
            }
            // 品牌名称
            if (searchMap.get("brandName") != null && !"".equals(searchMap.get("brandName"))) {
                criteria.andLike("brandName", "%" + searchMap.get("brandName") + "%");
            }
            // 规格
            if (searchMap.get("spec") != null && !"".equals(searchMap.get("spec"))) {
                criteria.andLike("spec", "%" + searchMap.get("spec") + "%");
            }
            // 商品状态 1-正常，2-下架，3-删除
            if (searchMap.get("status") != null && !"".equals(searchMap.get("status"))) {
                criteria.andLike("status", "%" + searchMap.get("status") + "%");
            }

            // 价格（分）
            if (searchMap.get("price") != null) {
                criteria.andEqualTo("price", searchMap.get("price"));
            }
            // 库存数量
            if (searchMap.get("num") != null) {
                criteria.andEqualTo("num", searchMap.get("num"));
            }
            // 库存预警数量
            if (searchMap.get("alertNum") != null) {
                criteria.andEqualTo("alertNum", searchMap.get("alertNum"));
            }
            // 重量（克）
            if (searchMap.get("weight") != null) {
                criteria.andEqualTo("weight", searchMap.get("weight"));
            }
            // 类目ID
            if (searchMap.get("categoryId") != null) {
                criteria.andEqualTo("categoryId", searchMap.get("categoryId"));
            }
            // 销量
            if (searchMap.get("saleNum") != null) {
                criteria.andEqualTo("saleNum", searchMap.get("saleNum"));
            }
            // 评论数
            if (searchMap.get("commentNum") != null) {
                criteria.andEqualTo("commentNum", searchMap.get("commentNum"));
            }

        }
        return example;
    }

}
